//
//  YCSendMegUtil.m
//  BeautyCar
//
//  Created by Apple on 2023/3/29.
//

#import "YCSendMegUtil.h"
#import "YCUtilityHeader.h"

@interface YCSendMegUtil ()<MFMessageComposeViewControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, copy) void (^resultBlock)(YCSendMegUtilResultType result);

@end

@implementation YCSendMegUtil

+ (YCSendMegUtil *)manager {
    static YCSendMegUtil *single = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        single = [[[self class] alloc] init];
    });
    return single;
}

- (void)sendMsgWithList:(NSArray<NSString *> *)list message:(nullable NSString *)message completion:(void (^)(YCSendMegUtilResultType result))completion {
    self.resultBlock = completion;
    
    if ([MFMessageComposeViewController canSendText]) {
        
        MFMessageComposeViewController *vc = [[MFMessageComposeViewController alloc] init];
        // 发送短信的号码，数组形式入参
        vc.recipients = list;
        vc.navigationBar.tintColor = [UIColor redColor];
        // 此处的body就是短信将要发生的内容
        vc.body = message;
        vc.messageComposeDelegate = self;
        [kKeyWindow.rootViewController presentViewController:vc animated:YES completion:nil];
        // 修改短信界面标题
        [[[[vc viewControllers] lastObject] navigationItem] setTitle:@"发短信"];
    } else {
        if (self.resultBlock) {
            self.resultBlock(YCSendMegUtilResultTypeUnsupport);
        }
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    [controller dismissViewControllerAnimated:YES completion:nil];
    
    YCSendMegUtilResultType type = YCSendMegUtilResultTypeSuccess;
    
    switch (result) {
        case MessageComposeResultSent:
            type = YCSendMegUtilResultTypeSuccess;
            break;
        case MessageComposeResultFailed:
            type = YCSendMegUtilResultTypeFailed;
            break;
        case MessageComposeResultCancelled:
            type = YCSendMegUtilResultTypeCancel;
            break;
        default:
            break;
    }
    
    if (self.resultBlock) {
        self.resultBlock(type);
    }
}

@end
